﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;

public partial class Order_ModifyAndClear : System.Web.UI.Page
{
    private string Code
    {
        get
        {
            return Request.QueryString["code"] != null ? Request.QueryString["code"].ToString() : "";
        }
    }

    private DataTable TempDataTable
    {
        get
        {
            DataTable tempTable = new BLL.RETURNDOCPAYDETAIL().CreateTempDataTable();
            //DataTable tempTable = null;
            if (ViewState["TempDataTable"] != null)
            {
                tempTable = (DataTable)ViewState["TempDataTable"];
            }
            return tempTable;
        }
        set
        {
            ViewState["TempDataTable"] = value;
        }
    }
    private DataSet DstPayDetails
    {
        get
        {
            DataSet dstPayDetails = null;
            if (ViewState["DstPayDetails"] != null)
            {
                dstPayDetails = (DataSet)ViewState["DstPayDetails"];
            }
            return dstPayDetails;
        }
        set
        {
            ViewState["DstPayDetails"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Check.CheckPermission("400101");
        if (!IsPostBack)
        {
            GetOrderInfo();
            BindDataList();
            btnCancel.Attributes.Add("onclick", "if(!confirm('确定要取消并返回上一页吗？'))return false;");
        }
    }

    private void GetOrderInfo()
    {
        string orderid = Request.QueryString["code"].ToString().Trim();
        Model.ORDERDOC od = new BLL.ORDERDOC().GetModel(orderid);

        lblorderid.Text = od.ORDER_ID;
        lblspje.Text = Decimal.Round(od.ORDER_AMT, 2).ToString();
        lblsl.Text = Decimal.Round(od.ORDER_QTY, 0).ToString();
        lblorderrq.Text = od.ORDER_CREATEDATE.ToString();
        lblorderje.Text = Decimal.Round(od.ORDER_AAMT, 2).ToString();
        lblksrq.Text = od.ORDER_CHECKDATE == DateTime.MinValue ? "" : od.ORDER_CHECKDATE.ToString();
        lblfhrq.Text = od.ORDER_SENDDATE == DateTime.MinValue ? "" : od.ORDER_SENDDATE.ToString();
        lbldeleterq.Text = od.ORDER_DELETEDATE == DateTime.MinValue ? "" : od.ORDER_DELETEDATE.ToString();

        HyperLink1.Text = od.ORDER_AID;
        HyperLink1.NavigateUrl = "OrderDetail.aspx?code=" + od.ORDER_AID.Trim();

        lblzk.Text = od.ORDER_DISC.ToString();

        lblcsrq.Text = od.ORDER_ACHECKDATE == DateTime.MinValue ? "" : od.ORDER_ACHECKDATE.ToString();
        lblclockrq.Text = od.ORDER_LOCKDATE == DateTime.MinValue ? "" : od.ORDER_LOCKDATE.ToString();
        ckbcs.Checked = od.ORDER_ACHECK == 0 ? false : true;
        ckbfh.Checked = od.ORDER_SEND == 0 ? false : true;
        ckbfp.Checked = od.ORDER_NINV == 0 ? false : true;
        txtfptt.Text = od.ORDER_INVTITLE;
        if (ckbfp.Checked) { ScriptManager.RegisterStartupScript(this, this.GetType(), "", "fpfunc();", true); }
        ckbks.Checked = od.ORDER_CHECK == 0 ? false : true;
        ckbsd.Checked = od.ORDER_LOCK == 0 ? false : true;
        ckbzf.Checked = od.ORDER_DELETE == 0 ? false : true;
        txtbz.Text = od.ORDER_NOTE;
        txtrlje.Text = Decimal.Round(od.ORDER_OFFERAMT, 2).ToString();
        txtwlfy.Text = Decimal.Round(od.ORDER_TRANCOST, 2).ToString();
        lblgmr.Text = od.ORDER_CUSTOMERCODE;
        Label2.Text = new BLL.V_CUSTOMER().GetModel(od.ORDER_CUSTOMERCODE).GKMC;
        lblgmr.NavigateUrl = "~/CustomerArchives/CustomerArchiveEdit.aspx?code=" + od.ORDER_CUSTOMERCODE;

        lblWeight.Text = String.Format("{0:0}", od.ORDER_WEIGHT);
        ckbjs.Checked = od.ORDER_CLEAR == 0 ? false : true;
        lblJSJE.Text = Decimal.Round(od.ORDER_CLEARAMT, 2).ToString();

        List<Model.TRANER> traner = new BLL.TRANER().GetAllList(true);
        ddlwlfs.DataSource = traner;
        ddlwlfs.DataTextField = "TRANER_NAME";
        ddlwlfs.DataValueField = "TRANER_CODE";
        ddlwlfs.DataBind();
        ddlwlfs.SelectedValue = od.ORDER_TRANERCODE;

        ddlfyxz.SelectedValue = od.ORDER_COSTNATURE;
        ddljylx.SelectedValue = od.ORDER_APAY.ToString();



        List<Model.ORDERFROM> of = new BLL.ORDERFROM().GetAllList(true);
        ddlddly.DataSource = of;
        ddlddly.DataTextField = "OF_NAME";
        ddlddly.DataValueField = "OF_CODE";
        ddlddly.DataBind();
        ddlddly.SelectedValue = od.ORDER_OFCODE;

        chkAssureDeal.Checked = od.ORDER_SECDEAL == 1 ? true : false;
    }
    private void BindDataList()
    {
        this.DstPayDetails = new BLL.PAYDETAIL().GetPayDetailsByOrderId(this.Code);
        dlistPayDetail.DataSource = this.DstPayDetails.Tables[0];
        dlistPayDetail.DataBind();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("400101", "00017"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {
            Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(this.Code);
            if (order == null)
            {
                throw new Exception("系统无法获取该订单信息！");
            }
            if (order.ORDER_CLEAR == 1)
            {
                throw new Exception("订单已经结算，不允许操作！");
            }
            //检查交易号
            bool Flag = true;
            foreach (DataListItem item in dlistPayDetail.Items)
            {
                TextBox dealNo = (TextBox)item.FindControl("txtDealId");
                if (dealNo.Text.Trim().Length <= 4)
                {
                    Flag = false;
                    break;
                }
            }
            if (!Flag)
            {
                Share.Alert(this.Page, "交易号不能少于4个字符长度"); return;
            }

            string strInfo = "";
            foreach (DataListItem item in dlistPayDetail.Items)
            {
                TextBox dealNo = (TextBox)item.FindControl("txtDealId");
                DropDownList Type = (DropDownList)item.FindControl("drpPayType");

                bool ret = new BLL.PAYDETAIL().CheckRepeat(dealNo.Text.Trim(), Type.SelectedValue, this.Code);
                if (ret)
                {
                    strInfo = "订单支付明细的交易号已存在,请核对交易号重新输入后保存！";
                }
            }

            if (strInfo.Length > 0)
            {
                Share.Alert(Page, strInfo.Substring(0, strInfo.Length - 1)); return;
            }

            string strAlert = "";
            foreach (DataListItem item in dlistPayDetail.Items)
            {
                TextBox dealNo = (TextBox)item.FindControl("txtDealId");
                DropDownList Type = (DropDownList)item.FindControl("drpPayType");
                string remittanceId = "";
                if (new BLL.REMITTANCE().CheckRepeat(dealNo.Text.Trim(), out remittanceId, Type.SelectedValue))
                {
                    strAlert = "订单支付明细的交易号在充值单中已经存在,所涉及到的充值单编号为:" + remittanceId + " 请核对交易号重新输入后保存!";
                }
            }
            if (strAlert.Length > 0)
            {
                Share.Alert(Page, strAlert); return;
            }
            //检查（到帐金额+退货金额）是否>=实际金额
            decimal getAmt = 0.00M;
            foreach (DataListItem item in dlistPayDetail.Items)
            {
                TextBox txtGet = (TextBox)item.FindControl("txtGetAmt");
                Label lblHraAmt = (Label)item.FindControl("lblHraAmt");
                getAmt = getAmt + decimal.Parse(txtGet.Text.Trim()) + decimal.Parse(lblHraAmt.Text);
            }
            //到帐日期检查
            strAlert = "";
            foreach (DataListItem item in dlistPayDetail.Items)
            {
                TextBox getDate = (TextBox)item.FindControl("txtGetDate");
                if (getDate.Text.Trim().Length == 0)
                {
                    strAlert = "到帐日期不能为空";
                }
            }
            if (strAlert.Length > 0)
            {
                Share.Alert(Page, strAlert); return;
            }
            /*
            if (getAmt < decimal.Parse(lblorderje.Text))
            {
                Share.Alert(Page, "到帐金额与退货金额之和不能小于实际金额"); return;
            }
            */
            //修改支付明细并结算
            StringBuilder StyleDB = new StringBuilder();
            StringBuilder ErpDB = new StringBuilder();
            string strWebServiceKey = ConfigurationManager.AppSettings["WebServiceKey"].ToString();
            LX_Manage.ERP.Service erpService = new LX_Manage.ERP.Service();

            foreach (DataListItem item in dlistPayDetail.Items)
            {
                Label detailId = (Label)item.FindControl("lblDetailId");
                DropDownList type = (DropDownList)item.FindControl("drpPayType");
                TextBox dealNo = (TextBox)item.FindControl("txtDealId");
                Label account = (Label)item.FindControl("lblAccount");
                TextBox get = (TextBox)item.FindControl("txtGetAmt");
                TextBox getDate = (TextBox)item.FindControl("txtGetDate");

                //修改订单支付明细
                if (getAmt >= decimal.Parse(lblorderje.Text))
                {//修改结算
                    StyleDB.Append(string.Format("update paydetail set PD_CHECK=1,PD_CHECKER='{0}',PD_CHECKDATE='{1}',PD_PAYTYPE='{2}',PD_DEALID='{3}',PD_ACCOUNT='{4}',PD_GET=1,PD_GETAMT={5},PD_GETDATE='{6}' where PD_ID='{7}' and PD_DETAILID='{8}'", Share.UserValue(0), DateTime.Now, type.SelectedValue, dealNo.Text, account.Text, get.Text, getDate.Text, this.Code, detailId.Text));
                    StyleDB.Append("|");
                    StyleDB.Append(string.Format("update paydetail set PD_CHECK=1,PD_CHECKER='{0}',PD_CHECKDATE='{1}',PD_GET=1,PD_GETDATE='{2}' where PD_ID='{3}' and PD_DETAILID='{4}'", Share.UserValue(0), DateTime.Now, getDate.Text, this.Code, detailId.Text));
                    StyleDB.Append("|");
                }
                else
                {//修改
                    StyleDB.Append(string.Format("update paydetail set PD_PAYTYPE='{0}',PD_DEALID='{1}',PD_ACCOUNT='{2}',PD_GET=1,PD_GETAMT={3},PD_GETDATE='{4}' where PD_ID='{5}' and PD_DETAILID='{6}'", type.SelectedValue, dealNo.Text, account.Text, get.Text, getDate.Text, this.Code, detailId.Text));
                    StyleDB.Append("|");
                }
            }
            //修改订单主表
            if (getAmt >= decimal.Parse(lblorderje.Text))
            {//修改结算
                StyleDB.Append(string.Format("update orderdoc set ORDER_CLEAR=1,ORDER_CLEARAMT={0},BYZD9='{1}' where  ORDER_ID='{2}'", getAmt, DateTime.Now, this.Code));
                StyleDB.Append("|");
            }
            else
            {//修改
                StyleDB.Append(string.Format("update orderdoc set ORDER_CLEARAMT={0} where  ORDER_ID='{1}'", getAmt, this.Code));
                StyleDB.Append("|");
            }

            bool retValue = false;
            if (getAmt > decimal.Parse(lblorderje.Text))
            {//结算
                decimal jyk = getAmt - decimal.Parse(lblorderje.Text);


                DataSet ds = new BLL.V_VIP_ACCOUNT().GetBalanceByCustomerId(order.ORDER_CUSTOMERCODE);
                string dm = new BLL.V_VIPSET().GetModelByGKDM(order.ORDER_CUSTOMERCODE).DM;
                if (ds.Tables[0].Rows.Count == 0)
                {
                    StyleDB.Append(string.Format("insert into V_VIP_ACCOUNT(DM,DQJE_1)values('{0}',{1})|", dm, jyk));
                    ErpDB.Append(string.Format("insert into V_VIP_ACCOUNT(DM,DQJE_1)values('{0}',{1})|", dm, jyk));
                }


                //同时生成一张已经审核的结余款调整单，同时修改用户当前金额和可用发货金额 
                string newID = new BLL.BALANCEADJUST().GetNewID();
                BLL.Common.ADDLSH("300400102");

                StyleDB.Append(string.Format("insert into BALANCEADJUST(BA_ID,BA_TYPE,BA_CREATER,BA_CREATEDATE,BA_CHECK,BA_CHECKER,BA_CHECKDATE,BA_RID) values('{0}','{1}','{2}','{3}',{4},'{5}','{6}','{7}')|", newID, "012", order.ORDER_CUSTOMERCODE, DateTime.Now, 1, order.ORDER_CUSTOMERCODE, DateTime.Now, this.Code));// 调整单主表



                DataSet dsDQJE = new BLL.V_VIP_ACCOUNT().GetBalanceByCustomerId(order.ORDER_CUSTOMERCODE);
                decimal balance = 0.00M;
                if (dsDQJE.Tables[0].Rows.Count > 0)
                {
                    balance = DBUtility.SqlHelper.GetDecimal(dsDQJE.Tables[0].Rows[0]["DQJE_1"]);
                }
                balance = balance + Convert.ToDecimal(jyk);

                StyleDB.Append(string.Format("insert into BADETAIL(BAD_ID,BAD_DETAILCODE,BAD_CUSTOMERCODE,BAD_AMT,BAD_BALANCE,BAD_NOTE) values('{0}',{1},'{2}',{3},{4},'{5}')|", newID, 1, order.ORDER_CUSTOMERCODE, jyk, balance,
                    "订单担保交易结算"));

                //同步更新用户当前金额
                StyleDB.Append(string.Format("update V_VIP_ACCOUNT set DQJE_1={0} where DM='{1}'|", balance, dm));
                ErpDB.Append(string.Format("update V_VIP_ACCOUNT set DQJE_1={0} where DM='{1}'|", balance, dm));

                decimal credit = new BLL.V_VIPSET().GetModelByGKDM(order.ORDER_CUSTOMERCODE).BYZD12;//信用额度
                decimal accountAmt = credit + balance;//账户当前余额加信用额度


                //同步更新可用发货金额 
                StyleDB.Append(string.Format("update v_vipset set BYZD13={0} where DM='{1}'|", accountAmt, dm));
                ErpDB.Append(string.Format("update v_vipset set BYZD13={0} where DM='{1}'|", accountAmt, dm));

            }
            string[] cmdStyle = StyleDB.ToString().TrimEnd('|').Split('|');
            string[] cmdErp = ErpDB.ToString().TrimEnd('|').Split('|');

            if (ErpDB.Length == 0)
            {
                retValue = new SQLServerDAL.ORDERDOC().Deliver(cmdStyle);
            }
            else
            {
                retValue = erpService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(strWebServiceKey, cmdStyle, cmdErp);
            }

            if (retValue)
            {
                Response.Redirect("OrderDetail.aspx?code=" + this.Code);
            }
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("OrderDetail.aspx?code=" + this.Code);
    }

    protected void dlistPayDetail_ItemDataBound(object sender, DataListItemEventArgs e)
    {

        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DataSet ds = new BLL.PAYTYPE_DEALTYPE().P_DealType_GetPayTypeByCode("002");

            DropDownList Type = (DropDownList)e.Item.FindControl("drpPayType");
            Type.DataSource = ds.Tables[0];
            Type.DataBind();
            
            HiddenField hdType=(HiddenField)e.Item.FindControl("hdPayType");
            Type.SelectedValue = hdType.Value;
        }
    }
    protected void drpPayType_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList Type = (DropDownList)sender;
        DataListItem item = (DataListItem)Type.Parent;
        ((Label)item.FindControl("lblAccount")).Text = GetAccount(Type.SelectedValue);
    }
    protected string GetAccount(string paytype)
    {
        string account = "";
        List<Model.PAYTYPE> payTypes = new BLL.PAYTYPE().GetAllList();
        foreach (Model.PAYTYPE tempType in payTypes)
        {
            if (tempType.PT_CODE == paytype)
            {
                account = tempType.PA_ACCOUNT;
                break;
            }
        }
        return account;
    }
}
